//
//  YDListViewModel.m
//  IngCard
//
//  Created by kf on 2017/5/23.
//  Copyright © 2017年 IngDan. All rights reserved.
//

#import "YDTableViewDataSource.h"
#import "YDBaseTableViewCell.h"

@interface YDSectionDataSource ()
@property(nonatomic, strong) NSMutableArray<id<YDViewDataSource>> * viewDataSources;
@end

@implementation YDSectionDataSource


-(void) insertViewDataSource:(id<YDViewDataSource>) dataSource
{
    [self.viewDataSources insertObject:dataSource atIndex:0];
}

- (void) addViewDataSource:(id<YDViewDataSource>) dataSource
{
    [self.viewDataSources addObject:dataSource];
}

- (BOOL) removeDataSource:(id<YDViewDataSource>) dataSrouce
{
    if ([self.viewDataSources containsObject:dataSrouce])
    {
        [self.viewDataSources removeObject:dataSrouce];
        return YES;
    }
    return NO;
}

- (void) replaceDataSource:(id<YDViewDataSource>) oldDataSource
             newDataSource:(id<YDViewDataSource>) newDataSrouce
{
    [self.viewDataSources enumerateObjectsUsingBlock:^(id<YDViewDataSource>  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       if (obj == oldDataSource)
       {
           self.viewDataSources[idx] = newDataSrouce;
           *stop = YES;
       }
    }];
}


- (NSInteger) indexOfDataSource:(id<YDViewDataSource>) dataSource
{
    __block NSInteger index = -1;
    [self.viewDataSources enumerateObjectsUsingBlock:^(id<YDViewDataSource>  _Nonnull item, NSUInteger idx, BOOL * _Nonnull stop) {
        if (item == dataSource)
        {
            index = idx;
            *stop = YES;
        }
    }];
    
    return index;
}
- (id<YDViewDataSource>) dataSourceAtIndex:(NSInteger) index
{
    if ( (index+1) > self.viewDataSources.count )
    {
        Log(@"CellModel取值越界");
        return nil;
    }
    
    return self.viewDataSources[index];
}


- (NSInteger) countOfRows
{
    return self.viewDataSources.count ? self.viewDataSources.count : 0;
}

#pragma mark - lazyLoading
-(NSMutableArray<id<YDViewDataSource>> *)viewDataSources
{
    if (!_viewDataSources)
    {
        _viewDataSources = [NSMutableArray array];
    }
    return _viewDataSources;
}
@end


@interface YDTableViewDataSource ()
@property(nonatomic, strong) NSMutableArray<YDSectionDataSource *>* sectionDataSources;
@property(nonatomic, weak) UITableView *tableView;
@end

@implementation YDTableViewDataSource

- (instancetype)initWithTableView:(UITableView *) tableView;
{
    
    if (self = [super init]) {
        _tableView = tableView;
    }
    return self;
}

- (NSIndexPath *)indexPathOfDataSource:(id<YDViewDataSource>) dataSource
{
    __block NSIndexPath * indexPath = nil;
    
    [self.sectionDataSources enumerateObjectsUsingBlock:^(YDSectionDataSource * _Nonnull item, NSUInteger idx, BOOL * _Nonnull stop) {
       
        NSInteger rowIndex = [item indexOfDataSource:dataSource];
        if (rowIndex != -1)
        {
            indexPath = [NSIndexPath indexPathForRow:rowIndex inSection:idx];
            *stop = YES;
        }
    }];
    
    return indexPath;
}

- (NSInteger) numberOfSections
{
    return self.sectionDataSources.count ? self.sectionDataSources.count : 0;
}


- (NSInteger) numberOfRowsWithSectionIndex:(NSInteger) sectionIndex
{
    if ((sectionIndex + 1) > self.sectionDataSources.count)
    {
        return 0;
    }
    
    return  [self.sectionDataSources[sectionIndex] countOfRows];
}


#pragma mark - 增删改查DataSource
- (void) addDataSource:(Class) dataSourceClassName
             atSection:(NSInteger) sectionIndex
                config:(void (^)(id<YDViewDataSource> dataSource)) config
{
    YDBaseTableViewCellDataSrouce *temp = [dataSourceClassName new];
    BlockGoGo(config, temp);
    [self addDataSource:temp atSection:sectionIndex];
}

- (void) addDataSource:(YDBaseTableViewCellDataSrouce *) dataSource
             atSection:(NSInteger) sectionIndex
{
    if (!dataSource || sectionIndex < 0)
    {
        return;
    }
    
    if (sectionIndex > (self.sectionDataSources.count + 1))
    {
        Log(@" ===== section 位置有问题 ===== ");
    }
    
    while ((sectionIndex +1) > self.sectionDataSources.count)
    {
        [self.sectionDataSources addObject:[YDSectionDataSource new]];
        
        if (self.tableView)
        {
            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:([self numberOfSections]-1)];
            [self.tableView insertSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }
    
    YDSectionDataSource *sectionModel = [self.sectionDataSources objectAtIndex:sectionIndex];
    [sectionModel addViewDataSource:dataSource];
    
    if (self.tableView)
    {
        NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:([sectionModel countOfRows]-1)
                                                    inSection:sectionIndex];
        [indexPaths addObject:indexPath];
        [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
    }
}


- (void) insertDataSource:(Class) dataSourceClassName
             atSection:(NSInteger) sectionIndex
                config:(void (^)(id<YDViewDataSource> dataSource)) config
{
    YDBaseTableViewCellDataSrouce *temp = [dataSourceClassName new];
    BlockGoGo(config, temp);
    [self insertDataSource:temp atSection:sectionIndex];
}


- (void) insertDataSource:(YDBaseTableViewCellDataSrouce *) dataSource
             atSection:(NSInteger) sectionIndex
{
    if (!dataSource || sectionIndex < 0)
    {
        return;
    }
    
    if (sectionIndex > (self.sectionDataSources.count + 1))
    {
        Log(@" ===== section 位置有问题 ===== ");
    }
    
    while ((sectionIndex +1) > self.sectionDataSources.count)
    {
        [self.sectionDataSources addObject:[YDSectionDataSource new]];
        
        if (self.tableView)
        {
            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:([self numberOfSections]-1)];
            [self.tableView insertSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }
    
    YDSectionDataSource *sectionModel = [self.sectionDataSources objectAtIndex:sectionIndex];
    [sectionModel insertViewDataSource:dataSource];
    
    if (self.tableView)
    {
        NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0
                                                    inSection:sectionIndex];
        [indexPaths addObject:indexPath];
        [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
    }
}


- (void) deleteDataSource:(YDBaseTableViewCellDataSrouce *) dataSource
{
    NSIndexPath *temp = [self indexPathOfDataSource:dataSource];
    if (temp)
    {
        [self deleteDataSourceByIndexPath:temp];
    }
}

- (void) deleteDataSourceByIndexPath:(NSIndexPath *) indexPath
{
    if (self.sectionDataSources.count > indexPath.section &&
        [self.sectionDataSources[indexPath.section] countOfRows] > indexPath.row)
    {
        YDSectionDataSource *sectionDataSrouce = self.sectionDataSources[indexPath.section];
        YDBaseTableViewCellDataSrouce *dataSource = [self dataSourceAtIndexPath:indexPath];
        
        if ([sectionDataSrouce removeDataSource:dataSource] && self.tableView)
        {
            NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
            [indexPaths addObject:indexPath];
            
            [self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
            
            if (![sectionDataSrouce countOfRows])
            {
                if(self.tableView)
                {
                    NSMutableIndexSet *indexs = [[NSMutableIndexSet alloc] init];
                    [indexs addIndex:(NSUInteger)indexPath.section];
                    [self.tableView deleteSections:indexs withRowAnimation:UITableViewRowAnimationAutomatic];
                }
                
                [self.sectionDataSources removeObject:sectionDataSrouce];
            }
        }
    }
}


- (void) reloadDataSource:(YDBaseTableViewCellDataSrouce *) dataSource
{
    NSIndexPath *temp = [self indexPathOfDataSource:dataSource];
    [self reloadDataSourceByIndexPath:temp];
}

- (void) reloadDataSourceByIndexPath:(NSIndexPath *) indexPath
{
    if (indexPath && self.tableView)
    {
        NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
        [indexPaths addObject:indexPath];
        
        [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

- (void) replaceDataSource:(YDBaseTableViewCellDataSrouce *) oldDataSource
                    config:(void (^)(id<YDViewDataSource> newDataSource)) config
{
    NSIndexPath *indexPath = [self indexPathOfDataSource:oldDataSource];
    if (indexPath)
    {
        YDBaseTableViewCellDataSrouce *temp = [[oldDataSource class] new];
        BlockGoGo(config, temp);
        
        YDSectionDataSource *sectionDataSource = self.sectionDataSources[indexPath.section];
        [sectionDataSource replaceDataSource:oldDataSource newDataSource:temp];
        
        if (self.tableView)
        {
            NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
            [indexPaths addObject:indexPath];
            [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }
}

- (id<YDViewDataSource>) dataSourceAtIndexPath:(NSIndexPath *) indexPath
{
    if((indexPath.section + 1) > self.sectionDataSources.count)
    {
        Log(@"Section 取值越界");
        return nil;
    }
    return [self.sectionDataSources[indexPath.section] dataSourceAtIndex:indexPath.row];
}

#pragma mark - 增、删、改、查sectionHeaderDataSource、sectionFooterDataSource

- (void) setSectionHeaderDataSource:(Class) dataSourceClassName
                          atSection:(NSInteger) sectionIndex
                             config:(void (^)(id<YDViewDataSource> dataSource)) config
{
    YDBaseTableViewCellDataSrouce *temp = [dataSourceClassName new];
    BlockGoGo(config, temp);
    [self addDataSource:temp atSection:sectionIndex];
}

- (void) setSectionFooterDataSource:(Class) dataSourceClassName
                          atSection:(NSInteger) sectionIndex
                             config:(void (^)(id<YDViewDataSource> dataSource)) config
{
    YDBaseTableViewCellDataSrouce *temp = [dataSourceClassName new];
    BlockGoGo(config, temp);
    [self addDataSource:temp atSection:sectionIndex];
}

- (id<YDViewDataSource>) headerDataSourceAtIndexPath:(NSUInteger) index
{
    if (self.sectionDataSources.count > index)
    {
//        YDSectionDataSource *sectionDataSource = (YDSectionDataSource *)self.sectionDataSources[index];
//        return sectionDataSource.headerDataSource;
    }
    return nil;
}

- (id<YDViewDataSource>) footerDataSourceAtIndexPath:(NSUInteger) index
{
    if (self.sectionDataSources.count > index)
    {
//        YDSectionDataSource *sectionDataSource = (YDSectionDataSource *)self.sectionDataSources[index];
//        return sectionDataSource.footerDataSource;
    }
    return nil;
}





#pragma mark - private
- (void) clear
{
    for (YDSectionDataSource * sectionModel in self.sectionDataSources) {
        [sectionModel.viewDataSources removeAllObjects];
    }
    [self.sectionDataSources removeAllObjects];
    
    _sectionDataSources = nil;
}

- (void) dealloc
{
    [self clear];
}

#pragma mark - lazy Loading
-(NSMutableArray<YDSectionDataSource *> *) sectionDataSources
{
    if (!_sectionDataSources)
    {
        _sectionDataSources = [NSMutableArray array];
    }
    return _sectionDataSources;
}
@end
